using BuildingBlocks.Abstractions.EventBase;
using Identity.Application.Contracts.Common;
using Identity.Application.Contracts.Events;
using Identity.Application.Contracts.Services;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace Identity.Infrastructure.EventHandlers
{
    public class UserRegisteredEventHandler : IIntegrationEventHandler<UserRegisteredEvent>
    {
         private readonly IEmailService _emailservice;
         private readonly IUserService _userService;
        private readonly BaseUrlOptions _urlOptions;
         private readonly ILogger<UserRegisteredEventHandler> _logger;

        public UserRegisteredEventHandler(
            IEmailService emailservice,
            IUserService userService,
            IOptions<BaseUrlOptions>  urlOptions,
            ILogger<UserRegisteredEventHandler> logger)
        {
            _emailservice = emailservice;
            _userService = userService;
            _urlOptions = urlOptions.Value;
            _logger = logger;
        }

        public async Task HandleAsync(UserRegisteredEvent @event)
        {
            var subject = "请激活您的账户";

            // 生成邮箱确认 token
            var token = await _userService.GenerateEmailConfirmationTokenAsync(@event.Id);//注册后未确认，提示用户主动确认，可以通过用户名+邮箱取得id，使用id获得token，然后进行下列步骤
            var encodedToken =await _emailservice.ConvertBase64UrlEncodeAsync(token);

            var frontendBaseUrl =_urlOptions.BaseUrl ?? "https://mighty-islands-fail.loca.lt/";//项目部署服务器地址，qq邮箱只能识别公网地址

            var callbackUrl = $"{frontendBaseUrl}/api/account/confirm-email?userId={@event.Id}&token={encodedToken}";

            var bodyText = $"欢迎注册，请点击以下链接激活您的账户：\n<a href='{callbackUrl}'>激活账户</a>";
            _logger.LogInformation("正在发送邮件");
            await _emailservice.SendEmailAsync(@event.Email, subject, bodyText);
            _logger.LogInformation("已经发送邮件");
        }
    }
}
